using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Windows;
using System.Xml;
using System.Windows.Forms;


namespace StikiDictionary
{    
    class DefaultLanguageDictionary
    {

        private Dictionary<string, string> theDictionary = new Dictionary<string, string>();

        public DefaultLanguageDictionary(string dictionaryFileName)
        { 
            FillDictionary(dictionaryFileName);        
        }

        private void FillDictionary(string dictionaryFileName)
        {
            string defaultTranslation = "";
            string translation = "";

            using (StreamReader sr = new StreamReader(dictionaryFileName, Encoding.Default))
            {
                String line;                
                while ((line = sr.ReadLine()) != null)
                {
                    defaultTranslation = sr.ReadLine().ToLower();                    
                    sr.ReadLine();
                    translation = sr.ReadLine();
                    sr.ReadLine();
                    if (!theDictionary.ContainsKey(defaultTranslation))                    
                        theDictionary.Add(defaultTranslation, translation);                                                                    
                }
            }        
        }

        public string GetTranslation(string Term)
        {
            string keyTerm = Term.ToLower();
            if (theDictionary.ContainsKey(keyTerm))
                return theDictionary[keyTerm];
            else
            {
                string colonTerm = keyTerm + ":";
                if (theDictionary.ContainsKey(colonTerm))
                    return theDictionary[colonTerm] + ":";
                else if (keyTerm.Contains(":"))
                {
                    colonTerm = keyTerm.Replace(":", "");
                    if (theDictionary.ContainsKey(colonTerm))
                        return theDictionary[colonTerm] + ":";
                }                
             }
             return "";
        }
    }


    class ResourceFileWriter
    {
        private ResourceFileLinker resourceFileLinker = new ResourceFileLinker();
        private DefaultLanguageDictionary defaultLanguageDictionary;

        private Label lblfilesScanned;
        private Label lblitemsFound;
        private ProgressBar progressBar;

        private StreamWriter logger;
        private StreamWriter translationNotFoundlogger;

        private const string cResourceFileExtension = ".resx";

        private const string cDefaultLanguageCode = "00";// English is the default language
        private const string cGermanLanguageCode = "de";
        private const string cIcelandicLanguageCode = "is";

        private const string cXMLTextIdentifier = ".Text";
        private const string cXMLValueIdentifier = "value";
        private const string cXMLDataIdentifier = "data";

        private const string cDictionaryFile = "C:\\German\\duits.txt";
        private const string cLogFile = "C:\\German\\Log.txt";
        private const string cLogFileTranslationNotFound = "C:\\German\\translationNotFoundLog.txt";

        public const bool cLinkerOn = false;

        public ResourceFileWriter(Label lblFilesScanned, Label lblItemsFound, ProgressBar progressbar)
        {
            lblfilesScanned = lblFilesScanned;
            lblitemsFound = lblItemsFound;
            progressBar = progressbar;
           
            defaultLanguageDictionary = new DefaultLanguageDictionary(cDictionaryFile);
            logger = new StreamWriter(cLogFile);
            translationNotFoundlogger = new StreamWriter(cLogFileTranslationNotFound);
        }

        public void ScanDirectory(string path)
        {
            if (File.Exists(path))
                ProcessFile(path);
            else if (Directory.Exists(path))
                ProcessDirectory(path);                                 
        }

        // Process all files in the directory passed in, recurse on any directories 
        // that are found, and process the files they contain.
        public void ProcessDirectory(string targetDirectory)
        {
            string[] fileEntries = Directory.GetFiles(targetDirectory);
            foreach (string fileName in fileEntries)
                ProcessFile(fileName);

            string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
            foreach (string subdirectory in subdirectoryEntries)
                ProcessDirectory(subdirectory);
        }
        
        //this function creates a resourcefile for a new language, 
        //by copying a corresponding default language resourcefile 
        //if the resourcefile is not for the default language false is returned
        public bool CreateNewResourceFile(string resourceFileName, string destLanguageCode, out string destResourceFileName)
        {
            destResourceFileName = "";
            if (resourceFileName.Contains(cResourceFileExtension))
            {
                string[] filePathParts = resourceFileName.Split('\\');
                string filename = filePathParts[filePathParts.Length - 1];
                string[] fileNameParts = filename.Split('.');

                if (fileNameParts.Length == 2)
                {
                    destResourceFileName = resourceFileName.Replace(".resx", "." + destLanguageCode + ".resx");
                    logger.Write("FILE CREATED " + destResourceFileName + ".tmp" + Environment.NewLine + "--------------------------" + Environment.NewLine);
                    if (File.Exists(destResourceFileName) == false)                        
                        File.Copy(resourceFileName, destResourceFileName + ".tmp", true);                    
                    return true;
                }
            }
            return false;
        }


        public void ProcessFile(string fileName)
        {
            bool containsTranslation = false;
            string newResourceFileName = "";

            if (CreateNewResourceFile(fileName, cGermanLanguageCode, out newResourceFileName))
            {                
                int fs = Convert.ToInt32(lblfilesScanned.Text) + 1;
                lblfilesScanned.Text = fs.ToString();
                lblfilesScanned.Update();

                XmlDocument resourceFile = new XmlDocument();
                resourceFile.Load(newResourceFileName +".tmp");
                XmlNode root = resourceFile.DocumentElement;
                for (int i = 0; i < root.ChildNodes.Count; i++)
                {
                    if (root.ChildNodes[i].Name == cXMLDataIdentifier)
                    {
                        if (!containsTranslation)
                            containsTranslation = ProcessData(root.ChildNodes[i]);
                        else
                            ProcessData(root.ChildNodes[i]);
                    }
                }
                //the next condition is to copy the tmp files that actually contain a translated item
                //if (containsTranslation)
                {
                    logger.Write("TMP FILE COPIED:  " + newResourceFileName + " CREATED" + Environment.NewLine + "--------------------------" + Environment.NewLine);
                    resourceFile.Save(newResourceFileName);
                    if (cLinkerOn)
                    {
                        if (resourceFileLinker.AddFileToProject(Directory.GetParent(newResourceFileName).FullName, resourceFileLinker.GetFileName(newResourceFileName)))
                            logger.Write("RESOURCE FILE ADDED TO PROJECT..." + Environment.NewLine + "--------------------------" + Environment.NewLine);
                        else
                            logger.Write("COULD NOT ADD RESOURCE FILE TO PROJECT..." + Environment.NewLine + "--------------------------" + Environment.NewLine);
                    }
                }
//                else
//                {
//                    logger.Write("TMP FILE DELETED FOR:  " + newResourceFileName + Environment.NewLine + "--------------------------" + Environment.NewLine);
//                }
            }
        }

        public bool ProcessData(XmlNode data)
        {
            bool containsTranslation = false;
            if (data.Attributes.Count > 0) 
            {
                if (data.Attributes[0].Value.Contains(cXMLTextIdentifier) || data.BaseURI.Contains(ResourceFileReader.cGridHeader))
                {
                    XmlNodeList valueNode = data.SelectNodes(cXMLValueIdentifier);
                    foreach (XmlNode n in valueNode)
                    {
                        containsTranslation = true;
                        string translation = defaultLanguageDictionary.GetTranslation(n.InnerXml);
                        if (translation != "")
                        {
                            logger.Write(n.InnerXml + Environment.NewLine + translation + Environment.NewLine + "------------------" + Environment.NewLine);
                            n.InnerXml = translation;
                        }
                        else
                        {
                            logger.Write("TRANSLATION NOT FOUND: " + n.InnerXml + Environment.NewLine + "------------------" + Environment.NewLine);
                            translationNotFoundlogger.Write("TRANSLATION NOT FOUND: " + n.InnerXml + Environment.NewLine + "------------------" + Environment.NewLine);
                        }                        
                    }
                }
            }
            return containsTranslation;
        }             

    }
}
